package com.md.repository.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fasterxml.jackson.core.type.TypeReference;
import com.md.base.BaseRepositoryImpl;
import com.md.config.database.CustomMapper;
import com.md.domain.model.po.RoleApis;
import com.md.model.bo.SizeBo;
import com.md.repository.RoleApiRepository;
import com.md.util.StringUtil;
import org.springframework.stereotype.Repository;
import org.springframework.util.ObjectUtils;

import java.util.List;

/**
 * @author 刘骄阳
 * 2022-06-12 1:22
 */
@Repository
public class RoleApiRepositoryImpl extends BaseRepositoryImpl<RoleApis> implements RoleApiRepository {
  public RoleApiRepositoryImpl(final CustomMapper<RoleApis> mapper) {
    super(mapper);
  }

  /**
   * 查询角色与api关系,根据apiId或者roleId
   *
   * @param apiId  apiId
   * @param roleId roleId
   * @return 角色与api的关系
   */
  @Override
  public List<RoleApis> queryByRoleIdOrApiId(final Long apiId, final Long roleId) {
    LambdaQueryWrapper<RoleApis> wrapper = new LambdaQueryWrapper<>();
    wrapper.eq(!ObjectUtils.isEmpty(apiId), RoleApis::getApiId, apiId)
      .eq(!ObjectUtils.isEmpty(roleId), RoleApis::getRoleId, roleId)
      .select(RoleApis::getRoleId, RoleApis::getApiId, RoleApis::getExtendsParentRole);
    return getMapper().selectList(wrapper);
  }

  /**
   * 根据角色id删除api权限
   *
   * @param roleIds 角色id列表
   * @param apiIds  权限列表
   */
  @Override
  public void deleteByRoleIdAndApiIds(final List<Long> roleIds,
                                      final List<Long> apiIds,
                                      final Boolean extendsParentRole) {
    if (ObjectUtils.isEmpty(apiIds) || ObjectUtils.isEmpty(roleIds)) {
      return;
    }
    LambdaQueryWrapper<RoleApis> wrapper = new LambdaQueryWrapper<>();
    wrapper.in(RoleApis::getRoleId, roleIds).in(!(ObjectUtils.isEmpty(apiIds)), RoleApis::getApiId, apiIds).
      eq(!(ObjectUtils.isEmpty(extendsParentRole)), RoleApis::getExtendsParentRole, extendsParentRole);
    getMapper().delete(wrapper);
  }

  /**
   * 查询role下的api的数量
   *
   * @param roleIds 角色ids
   * @return 角色下api的数量
   */
  @Override
  public List<SizeBo> querySize(final List<Long> roleIds) {
    QueryWrapper<RoleApis> wrapper = new QueryWrapper<>();
    wrapper.select("role_id as groupId", "COUNT(api_id) as size").groupBy("role_id").lambda().
      in(RoleApis::getRoleId, roleIds);
    return StringUtil.jsonToObject(StringUtil.objectToJson(getMapper().selectMaps(wrapper)),
      new TypeReference<List<SizeBo>>() {
      });
  }
}
